import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_oldman_health/api/constant.dart';
import 'package:flutter_oldman_health/api/member_service.dart';
import 'package:flutter_oldman_health/models/member_model.dart';
import 'package:flutter_oldman_health/models/relation_model.dart';
import 'package:flutter_oldman_health/models/response_data_model.dart';
import 'package:flutter_oldman_health/utils/remote_control_utils.dart';
import 'package:flutter_oldman_health/utils/utils.dart';
import 'package:flutter_oldman_health/widget/common_container.dart';

import 'family_remote_control_page.dart';
import 'health_record_page.dart';
import 'map/map_type_show_page.dart';
import 'message_reminder_page.dart';

class FamilyMemberPage extends StatefulWidget {
  FamilyRelationItem item;

  FamilyMemberPage(FamilyRelationItem value) {
    item = value;
  }

  @override
  State<StatefulWidget> createState() => _FamilyMemberPageState(item);
}

class _FamilyMemberPageState extends State<FamilyMemberPage> {
  bool showRemarks = false;
  bool refreshRemarks = false;
  String remarksName;

  String _checkedRelationship = "";
  List relationshipList = [
    "爸爸",
    "妈妈",
    "爷爷",
    "奶奶",
    "姥姥",
    "姥爷",
    "叔叔",
    "婶婶",
    "姑姑",
    "姑父",
    "姨母",
    "姨夫",
    "伯伯",
    "伯母"
  ];
  TextEditingController _controller;
  FamilyRelationItem relationItem = FamilyRelationItem("-1", "成员姓名");
  MemberInfo memberInfo;

  // 城市经纬度
  BMFCoordinate geoPt;

  BMFMapOptions mapOptions;
  BMFMapController myMapController;
  BMFMarker marker;

  _FamilyMemberPageState(FamilyRelationItem item) {
    relationItem = item;
    _checkedRelationship = relationItem.alias;
    // remarksName = relationItem.alias;
    _controller = TextEditingController(text: relationItem.alias);
  }

  @override
  void initState() {
    super.initState();
    queryMemberInfo();
  }

  void queryMemberInfo() async {
    var response =
        await FamilyMemberService.queryMemberInfo(relationItem.memberId);
    if (null != response && response.statusCode == 200) {
      MemberModel memberModel = MemberModel.fromJson(response.data);

      if (null != memberModel && memberModel.success()) {
        if (memberModel.data != null && null != memberModel.data.latitude) {
          print(
              "geoPt ${memberModel.data.latitude}, ${memberModel.data.longitude}");

          mapOptions = BMFMapOptions(
              mapType: BMFMapType.Standard,
              zoomLevel: 13,
              maxZoomLevel: 21,
              minZoomLevel: 4,
              showMapPoi: true,
              logoPosition: BMFLogoPosition.LeftBottom,
              mapPadding: BMFEdgeInsets(top: 0, left: 50, right: 50, bottom: 0),
              overlookEnabled: true,
              overlooking: -15,
              center: BMFCoordinate(
                  memberModel.data.latitude, memberModel.data.longitude));

          setState(() {
            memberInfo = memberModel.data;
            if (_controller.text == null) _controller.text = memberInfo.name;
            geoPt = BMFCoordinate(memberInfo.latitude, memberInfo.longitude);
          });
          if (myMapController != null) {
            myMapController.updateMapOptions(initMapOptions(geoPt));
            marker.updatePosition(geoPt);
          }
        } else {
          setState(() {
            memberInfo = null;
            geoPt = null;
          });
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: true,
        //重点 监听返回键
        body: WillPopScope(
            onWillPop: () async {
              if (showRemarks) {
                setState(() {
                  showRemarks = false;
                });
                return false;
              }
              Navigator.pop(context, refreshRemarks);
              myMapController.removeMarker(marker);
              return false;
            },
            child: SingleChildScrollView(
                child: Container(
                    padding: EdgeInsets.only(top: 8),
                    color: Constant.backgroundColor,
                    child: Column(children: [
                      _getTitle(_checkedRelationship),
                      Stack(children: [
                        _showNormalMessage(),
                        if (showRemarks) _showRemarks()
                      ])
                    ])))));
  }

  Widget _showRemarks() {
    return Container(
      padding: EdgeInsets.all(16),
      //重点 获取屏幕宽高
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height - 95,
      color: Color(0xddffffff),
      child: Column(children: [
        Text("备注名",
            style: TextStyle(
                color: Color(0xff666666),
                fontSize: 18,
                fontWeight: FontWeight.normal)),
        Container(
            margin: EdgeInsets.fromLTRB(50, 0, 50, 16),
            child: TextField(
                controller: _controller,
                maxLines: 1,
                maxLength: 6,
                autofocus: false,
                textAlign: TextAlign.center,
                inputFormatters: [LengthLimitingTextInputFormatter(6)],
                style: TextStyle(
                    fontSize: 18,
                    color: Colors.black87,
                    fontWeight: FontWeight.w300),
                // obscureText: true,
                decoration: InputDecoration(
                    // hintText: remarksName,
                    hintStyle: TextStyle(fontSize: 18),
                    //重点 修改下划线
                    focusedBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Color(0xaa41BAB0))),
                    enabledBorder: UnderlineInputBorder(
                        borderSide: BorderSide(color: Color(0xff41BAB0)))
                    //InputBorder.none  OutlineInputBorder() ///border: OutlineInputBorder()
                    ))),
        Container(
            alignment: Alignment.centerLeft,
            child: Text("关系:",
                textAlign: TextAlign.start, style: TextStyle(fontSize: 18))),
        Wrap(
          children: getRelationshipListWidgets(),
        ),
        CommonContainer(
            GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () async {
                  if (null == _controller.text || _controller.text.isEmpty) {
                    EasyLoading.showError("备注名不可为空");
                    return;
                  }
                  var response = await FamilyMemberService.editFamilyRelation(
                      relationItem.memberId, _controller.text);
                  if (null != response && response.statusCode == 200) {
                    ResponseDataModel<String> model =
                        ResponseDataModel.fromJson(response.data);
                    if (model.success()) {
                      refreshRemarks = true;
                      setState(() {
                        remarksName = _controller.text;
                        _checkedRelationship = _controller.text;
                        showRemarks = !showRemarks;
                      });
                    } else {
                      EasyLoading.showInfo(model.msg);
                    }
                  } else {
                    EasyLoading.showInfo("修改失败");
                  }
                },
                child: FractionallySizedBox(
                    widthFactor: 1,
                    child: Text("确定修改",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 19,
                            color: Colors.white)))),
            margin: EdgeInsets.only(top: 20),
            padding: EdgeInsets.all(8),
            colorBg: Color(0xff41BAB0),
            colorBorder: Color(0xFFEEEEEE),
            radiusCircular: 58)
      ]),
    );
  }

  Widget _showNormalMessage() {
    return Padding(
        padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
        child: Column(children: [
          CommonContainer.item(context, "消息", "images/ic_family_message.png",
              MessageReminderPage(relationItem), 24),
          CommonContainer.item(
              context,
              "健康记录",
              "images/ic_family_health_record.png",
              HealthRecordPage(relationItem),
              24),
          CommonContainer.item(
              context,
              "远程操控",
              "images/ic_family_remote_control.png",
              FamilyRemoteControlPage(
                  familyId: relationItem.memberId, active: true),
              24),
          if (null != geoPt)
            CommonContainer(
                GestureDetector(
                    behavior: HitTestBehavior.translucent,
                    onTap: () {
                      geoPt == null
                          ? EasyLoading.showInfo("暂无位置信息")
                          : Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (_) => //BasicLoc()
                                      ShowMapTypePage(
                                          customMapOptions: mapOptions,
                                          relationItem: relationItem,
                                          geoPt: geoPt)));
                    },
                    child: Column(children: [
                      Padding(
                        padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                        child: Row(
                          children: <Widget>[
                            Icon(Icons.my_location,
                                size: 28, color: Color(0xff41BAB0)),
                            Expanded(
                              flex: 1,
                              child: Container(
                                margin: EdgeInsets.only(left: 18),
                                child: Text(
                                  "区域防护",
                                  style: TextStyle(fontSize: 19),
                                ),
                              ),
                            ),
                            Icon(Icons.arrow_forward_ios,
                                color: Color(0xFFAAAAAA))
                          ],
                        ),
                      ),
                      generateMap()
                    ])),
                margin: EdgeInsets.only(top: 12),
                padding: EdgeInsets.all(4))
        ]));
  }

  /// 创建地图
  Container generateMap() {
    return Container(
        margin: EdgeInsets.only(top: 12),
        width: 470,
        height: 266,
        child: null == geoPt
            ? Text("暂无位置信息",
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 28,
                    fontWeight: FontWeight.w300,
                    color: Colors.black54))
            : BMFMapWidget(
                onBMFMapCreated: onBMFMapCreated,
                mapOptions: initMapOptions(geoPt),
              ));
  }

  /// 设置地图参数
  BMFMapOptions initMapOptions(BMFCoordinate center) {
    if (null != this.mapOptions) {
      this.mapOptions.center = center;
      return this.mapOptions;
    }
    this.mapOptions = BMFMapOptions(
        mapType: BMFMapType.Standard,
        zoomLevel: 15,
        maxZoomLevel: 21,
        minZoomLevel: 4,
        logoPosition: BMFLogoPosition.LeftBottom,
        mapPadding: BMFEdgeInsets(top: 0, left: 50, right: 50, bottom: 0),
        overlookEnabled: true,
        overlooking: -15,
        center: center);
    return mapOptions;
  }

  /// 创建完成回调
  void onBMFMapCreated(BMFMapController controller) {
    myMapController = controller;

    /// 地图加载回调
    myMapController.setMapDidLoadCallback(callback: () {
      print('mapDidLoad-地图加载完成');
    });
    marker = BMFMarker(
        position: geoPt,
        title: null == memberInfo ? _checkedRelationship : memberInfo.name,
        subtitle: null == memberInfo ? '' : memberInfo.phone,
        identifier: null == memberInfo ? '成员' : memberInfo.name,
        icon: 'images/icon_binding_point.png',
        enabled: false,
        draggable: false);

    myMapController.addMarker(marker);
  }

  List<Widget> getRelationshipListWidgets() {
    var relationshipWidgets = relationshipList.map((e) => GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            setState(() {
              //_checkedRelationship = e;
              _controller.text = e;
            });
          },
          child: Container(
            decoration: BoxDecoration(
                border: Border.all(color: Color(0xff41BAB0)),
                borderRadius: BorderRadius.circular(8)),
            padding: EdgeInsets.fromLTRB(16, 4, 16, 4),
            margin: EdgeInsets.fromLTRB(16, 8, 16, 8),
            child: Text(
              e,
              textAlign: TextAlign.center,
              style: TextStyle(
                  color: (_checkedRelationship == e
                      ? Color(0xff41BAB0)
                      : Color(0xff666666))),
            ),
          ),
        ));
    return relationshipWidgets.toList();
  }

  void deleteFamilyMember() async {
    var response =
        await FamilyMemberService.deleteMember(relationItem.memberId);
    if (null != response && response.statusCode == 200) {
      ResponseDataModel<String> model =
          ResponseDataModel.fromJson(response.data);
      if (model.success()) {
        RemoteControlTool().replyFamilyAddRequest(relationItem.memberId);
        EasyLoading.showSuccess("成功删除");
        Navigator.of(context).pop(true);
      } else {
        EasyLoading.showInfo(model.msg);
      }
    } else {
      EasyLoading.showInfo("删除失败");
    }
  }

  Future editFamilyMemberDialog() async {
    var result = await showDialog(
        context: context,
        builder: (context) {
          return SimpleDialog(
            // title: Text('添加角色'),
            children: <Widget>[
              SimpleDialogOption(
                  child: Padding(
                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      child: Text("删除成员",
                          textAlign: TextAlign.center,
                          style: TextStyle(fontSize: 17))),
                  onPressed: () {
                    Navigator.of(context).pop(true);
                    // EventBus().showRemindDialog(context, () async {
                    //   var response = await FamilyMemberService.deleteMember(
                    //       relationItem.memberId);
                    //   if (null != response && response.statusCode == 200) {
                    //     ResponseDataModel<String> model =
                    //         ResponseDataModel.fromJson(response.data);
                    //     if (model.success()) {
                    //       RemoteControlTool()
                    //           .replyFamilyAddRequest(relationItem.memberId);
                    //       EasyLoading.showInfo("成功删除");
                    //       Navigator.of(context).pop(true);
                    //     } else {
                    //       EasyLoading.showInfo(model.msg);
                    //     }
                    //   } else {
                    //     EasyLoading.showInfo("删除失败");
                    //   }
                    // });
                    showRemindDialog(context);
                  }),
              SimpleDialogOption(
                  child: Container(
                height: 1,
                color: Color(0xffdddddd),
              )),
              SimpleDialogOption(
                  child: Text("备注",
                      textAlign: TextAlign.center,
                      style: TextStyle(fontSize: 17)),
                  onPressed: () async {
                    Navigator.pop(context);
                    setState(() {
                      showRemarks = !showRemarks;
                    });
                  }),
            ],
          );
        });
    print("result=> $result");
    return result;
  }

  Widget _getTitle([String title = "成员姓名"]) {
    return Container(
        color: Constant.appbarColor,
        padding: EdgeInsets.fromLTRB(16, 46, 16, 16),
        child: FractionallySizedBox(
            widthFactor: 1,
            child: Stack(alignment: Alignment.center, children: [
              Positioned(
                  left: 2,
                  child: GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        if (showRemarks) {
                          setState(() {
                            showRemarks = false;
                          });
                        } else {
                          Navigator.pop(context, refreshRemarks);
                          // myMapController.removeMarker(marker);
                        }
                      },
                      child: Container(
                          child: Icon(Icons.arrow_back_ios),
                          padding: EdgeInsets.fromLTRB(15, 10, 20, 10)))),
              Text(title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: 22,
                      color: Colors.black87,
                      fontWeight: FontWeight.normal)),
              if (!showRemarks)
                Positioned(
                    right: 2,
                    child: GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTap: () {
                          if (!showRemarks) {
                            editFamilyMemberDialog().then((value) {
                              print(value);
                            });
                          } else {
                            setState(() {
                              showRemarks = false;
                            });
                          }
                        },
                        child: Container(
                          padding: EdgeInsets.fromLTRB(12, 4, 12, 4),
                          child: Text(
                            "菜单",
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 18,
                                fontWeight: FontWeight.normal),
                          ),
                          decoration: BoxDecoration(
                              color: Color(0xff41BAB0),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8))),
                        )))
            ])));
  }

  Future showRemindDialog(BuildContext context) async {
    var result = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: Text("删除成员", style: TextStyle(fontSize: 17)),
              content: Text("您确定要删除该成员？", style: TextStyle(fontSize: 17)),
              actions: <Widget>[
                ElevatedButton(
                    onPressed: () {
                      Navigator.pop(context);
                    },
                    child: Padding(
                        padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                        child: Text("取消")),
                    style: ButtonStyle(
                      shape: MaterialStateProperty.all(StadiumBorder(
                          side: BorderSide(
                              //设置 界面效果 圆角弧度
                              style: BorderStyle.solid,
                              color: Colors.grey[400]))),
                      foregroundColor:
                          MaterialStateProperty.all(Color(0xff333333)),
                      backgroundColor: MaterialStateProperty.all(Colors.white),
                      textStyle:
                          MaterialStateProperty.all(TextStyle(fontSize: 17)),
                    )),
                ElevatedButton(
                    onPressed: () async {
                      deleteFamilyMember();
                      Navigator.pop(context);
                    },
                    child: Padding(
                        padding: EdgeInsets.fromLTRB(12, 8, 12, 8),
                        child: Text("确定")),
                    style: ButtonStyle(
                        backgroundColor:
                            MaterialStateProperty.all(Colors.orange),
                        textStyle:
                            MaterialStateProperty.all(TextStyle(fontSize: 17)),
                        shape: MaterialStateProperty.all(StadiumBorder(
                            side: BorderSide(
                          //设置 界面效果 圆角弧度
                          style: BorderStyle.solid,
                          color: Color(0xffFF7F24),
                        ))))),
              ]);
        });
    return result;
  }
}
